import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Asset } from 'src/entity/Asset'
import { InStore } from 'src/entity/InStore'
import { Purchase } from 'src/entity/Purchase'
import { Connection, IsNull, Repository } from 'typeorm'
import { v4 as uuidV4 } from 'uuid'

@Injectable()
export class InStoreService {
  constructor(
    @InjectRepository(InStore)
    private inStoreRepository: Repository<InStore>,
    private connection: Connection,
  ) { }

  async add(data) {
    await this.connection.transaction(async (manager) => {
      const list = []
      data.assetList.forEach((item) => {
        for (let i = 0; i < item.number; i++) {
          const assetCode = uuidV4()
          list.push({
            ...item,
            assetCode,
            branchId: data.branchId,
            branchName: data.branchName,
            assetStatus: '1',
          })
        }
      })
      const assetSqlData = await manager.insert(Asset, list)
      let assetIds
      if (assetSqlData.generatedMaps.length) {
        assetIds = assetSqlData.generatedMaps.map((item) => {
          return item.id
        })
      } else {
        assetIds = null
      }
      const inStore = {
        inStoreName: data.inStoreName,
        inStoreType: data.inStoreType,
        inStoreDate: data.inStoreDate,
        purchaseId: data.purchaseId,
        purchaseName: data.purchaseName,
        inStoreNumber: data.inStoreNumber,
        assetIds: assetIds.join(','),
        branchId: data.branchId,
        branchName: data.branchName,
        remark: data.remark,
      }
      manager.insert(InStore, inStore)
      manager.update(
        Purchase,
        {
          id: data.purchaseId,
        },
        { isInStore: true },
      )
    })
  }

  async del(id: number) {
    return await this.inStoreRepository.update(
      {
        id: id,
      },
      {
        isDelete: true,
      },
    )
  }

  async update(data) {
    return data
  }

  // 更新某个属性
  async updateProperty(id, property, value) {
    return await this.inStoreRepository.update(
      {
        id,
      },
      {
        [property]: value,
      },
    )
  }

  // 分页查询
  async getPageList({
    pageRequest: { pageIndex, pageSize },
    inStoreName,
    inStoreType,
    purchaseName,
    orgId,
  }) {
    const sqlAllData = await this.inStoreRepository.find({
      where: {
        isDelete: IsNull(),
        branchId: orgId,
        inStoreName: inStoreName,
        inStoreType: inStoreType,
        purchaseName: purchaseName,
      },
    })
    const sqlData = await this.inStoreRepository.find({
      where: {
        isDelete: IsNull(),
        branchId: orgId,
        inStoreName: inStoreName,
        inStoreType: inStoreType,
        purchaseName: purchaseName,
      },
      skip: (pageIndex - 1) * pageSize,
      take: pageSize,
      withDeleted: false,
    })

    return {
      content: sqlData.map((item) => {
        return {
          ...item,
          purchaseId: item.purchaseId?.toString() || null,
        }
      }),
      total: sqlAllData.length,
    }
  }

  // 获取资产详情
  async getAssetDetail(id) {
    let data: any = {
      assetList: [],
    }
    await this.connection.transaction(async (manager) => {
      data = await manager.findOne(InStore, {
        where: {
          isDelete: IsNull(),
          id,
        },
      })
      const ids = (data.assetIds as string).split(',')
      data.assetList = await manager.findByIds(Asset, ids)
    })
    return data
  }
}
